package Client;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;

import Server.Chat_Server;

public class Chat_client implements Runnable {

	Scanner input;
	Scanner send = new Scanner(System.in);
	PrintWriter out;
	Socket sock;

	public Chat_client(Socket soc) {
		this.sock = soc;
	}

	@Override
	public void run() {
		try {
			try {
				input = new Scanner(sock.getInputStream());
				out = new PrintWriter(sock.getOutputStream());
				out.flush();
				CheckStream();
			} finally {
				sock.close();
			}
		} catch (IOException e) {
			System.out.println(e);
			e.printStackTrace();
		}

	}

	private void CheckStream() {
		while (true) {
			receive();
		}
	}

	private void receive() {
		if (input.hasNext()) {
			String message = input.nextLine();
			if (message.contains("#?!")) {
				String temp1 = message.substring(3);
				temp1 = temp1.replace("[", "");
				temp1 = temp1.replace("]", "");
				String[] curentUsers = temp1.split(", ");
				// for
				Client_Gui.onlineUsersArea.setText("");;
				for (String user : curentUsers) {
					// https://www.youtube.com/watch?v=Uo5DY546rKY
					// JButton online_but = new JButton(new
					// ImageIcon("online_button.png"));
					Client_Gui.onlineUsersArea.append( user + "\n");
				}
			} else
				Client_Gui.chatArea.append(message + "\n");

		}
	}

	public void send(String text) {
		Date dNow = new Date();
		SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss a");
		out.println(Client_Gui.userName + " [" + ft.format(dNow) + "] : " + text);
		out.flush();
		Client_Gui.inputTextArea.setText("");

	}

	public void disconnect() throws IOException {
		
		out.println(Client_Gui.userName + " has disconnected.");
		out.flush();
		sock.close();
		JOptionPane.showMessageDialog(null, "You disconnected");
		System.exit(0);
	}	

}
